//
//  Brands_BrandsMainTitle_Scr_WX.m
//  ZITHER
//
//  Created by weixin on 2019/4/8.
//  Copyright © 2019 weixn. All rights reserved.
//

#import "Brands_BrandsMainTitle_Scr_WX.h"
#define BtnHeight 30

@implementation Brands_BrandsMainTitle_Scr_WX

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _arrM = [NSMutableArray array];
//        self.backgroundColor = ;
        self.bounces = NO;
        self.showsHorizontalScrollIndicator = NO;
    }
    return self;
}

-(void)setArrM:(NSMutableArray *)arrM
{
    _arrM = arrM;
    
    self.contentOffset = CGPointMake(0, 0);
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *lastBtn = nil;
    
    for (int i = 0; i<arrM.count; i++) {
        
        
        BaseBtn * btn = [BaseBtn initCustomBtnTitlestype:@[self.arrM[i],self.arrM[i]] color:@[[UIColor blackColor],[UIColor whiteColor]]];
        
        btn.tag = 100+i;
        
        btn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        
        CGFloat width = [self widthBtnHeight:self.frame.size.height font:[UIFont fontWithName:@"PingFang-SC-Regular" size:15] text:arrM[i]]+40;

        if (lastBtn == nil) {
            btn.backgroundColor = baseColorTheme;
            btn.frame = CGRectMake(15,25, width, BtnHeight);
            btn.selected = YES;
            self.lastButton = btn;
        }else{
            btn.backgroundColor = HexColor(0xf5f5f5);
            btn.frame = CGRectMake(CGRectGetMaxX(lastBtn.frame)+10,25, width, BtnHeight);

        }
        
        [btn setCornerRadiusWithRadius:4 isMasks:YES];
        [[btn addTag]subscribeNext:^(id  _Nullable x) {
            [self changeBtn:btn.tag];
            if (self.block) {
                self.block(btn.tag);
            }
            
        }];
        
        [self addSubview:btn];
        
        lastBtn = btn;
        
    }
    self.contentSize = CGSizeMake(CGRectGetMaxX(lastBtn.frame)+20, self.height);
}



-(void)changeBtn:(NSInteger)index{
    UIButton *btn = [self viewWithTag:index];
    if (btn == self.lastButton){
        return;
    }
    self.lastButton.selected = NO;
    btn.selected = YES;
    
    btn.backgroundColor = baseColorTheme;
    self.lastButton.backgroundColor = HexColor(0xf5f5f5);
    
    
    //设置图标超出屏幕滚动到中间
    CGRect rect = btn.frame;
    rect.size.width += self.frame.size.width-30;
    rect.origin.x -= self.frame.size.width/2.0+20;
    [self scrollRectToVisible:rect animated:YES];
    
    self.lastButton = btn;
    
}

-(CGFloat)widthBtnHeight:(CGFloat)height font:(UIFont*)font text:(NSString*)str
{
    return  [str boundingRectWithSize:CGSizeMake(10000,height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size.width;
}

@end
